'use strict';

const { apiFail } = require('../extend/context');

const Controller = require('egg').Controller;

class MomentController extends Controller {
  // 发布朋友圈
  async create() {
    const { ctx, app } = this;
    let current_user_id = ctx.authUser.id;
    // 参数验证
    ctx.validate({
      content: {
        type: 'string',
        required: false,
        desc: '内容'
      },
      image: {
        type: 'string',
        required: false,
        desc: '图片'
      },
      video: {
        type: 'string',
        required: false,
        desc: '视频'
      },
      type: {
        type: 'string',
        required: true,
        range: {
          in:['content','image','video']
        },
        desc: '朋友圈类型'
      },
      location: {
        type: 'string',
        required: false,
        desc: '位置'
      },
      remind: {
        type: 'string',
        required: false,
        desc: '提醒谁看'
      },
      see: {
        type: 'string',
        required: false,
        defValue: "all",
        desc: '谁可以看'
      }
    });
    let { content,image,video,type,location,remind,see } = ctx.request.body;

    if(!ctx.request.body[type]){
      return ctx.apiFail(`${type} 不能为空`);
    }

    let moment = await app.model.Moment.create({
      content,
      image,
      video,
      location,
      remind,
      see,
      user_id: current_user_id
    });
    if(!moment){
      return ctx.apiFail('发布失败')
    }

    // 推送到好友的时间轴
    this.toTimeline(moment)

    ctx.apiSuccess('ok')
  }

  // 推送到好友的时间轴
  async toTimeline(moment){
    const { ctx, app } = this;
    let current_user_id = ctx.authUser.id;
    // 获取当前用户所有好友 id
    let friends = await app.model.Friend.findAll({
      where: {
        user_id: current_user_id,
        isblack: 0
      },
      attributes:['friend_id']
    });
    /**
     * all     全部人可以看 ['all']
     * only:1，2，3 指定人可以看 ['only','1，2，3 ']
     * except: 1,2,3  谁不可以看  ['except','1，2，3 ']
     * none   仅自己可见  ['none']
     */
    // 谁可以看
    let sees = moment.see.split(':');
    let o = {
      only: [],
      except: []
    }
    let oType = sees[0]
    if((sees[0] === 'only' || sees[0] === 'except') && sees[1]){
      o[sees[0]] = (sees[1].split(',')).map(v=>parseInt(v)); // 转成int类型
    }

    let addData = friends.filter(item=>{
      return oType === 'all' || (oType === 'only' && o.only.includes(item.friend_id)) || (oType === 'except' && !o.except.includes(item.friend_id));
    })

    // 好友
    addData = addData.map(item=>{
      return {
        user_id: item.friend_id,
        moment_id: moment.id,
        own:0
      }
    });
    // 本人
    addData.push({
      user_id: current_user_id,
      moment_id: moment.id,
      own:1
    })
    // 批量推送到时间轴
    await app.model.MomentTimeline.bulkCreate(addData)

    // 消息推送
    let message = {
      avatar: ctx.authUser.avatar,
      user_id: current_user_id,
      type: "new"
    }

    addData.forEach(item=>{
      ctx.sendAndSaveMessame(item.user_id,message, 'moment')
    })

    // 提醒用户
    if(moment.remind){
      let arr = moment.remind.split(',')  // 转成一维数组
      arr.forEach(user_id=>{
        ctx.sendAndSaveMessame(user_id, {
          avatar: ctx.authUser.avatar,
          user_id: current_user_id,
          type: 'remind'
        }, 'moment');
      })
    }
  }

  // 点赞
  async like(){
    const { ctx, app } = this;
    let current_user_id = ctx.authUser.id;
    ctx.validate({
      id: {
        type: "int",
        required: true,
        desc: "朋友圈id"
      }
  });
    let { id } = ctx.request.body;
    let momentTimeline = await app.model.MomentTimeline.findOne({
      where: {
        user_id: current_user_id,
        moment_id: id
      },
      include: [{
        model: app.model.Moment,
        attributes: ['user_id'],
        include: [{
            model: app.model.MomentLike,
            attributes: ['user_id'],
        }]
      }]
    });
    if(!momentTimeline){
      return ctx.apiFail('朋友圈消息不存在')
    }

    // 判断是否点赞过
    let like = await app.model.MomentLike.findOne({
      where: {
        user_id: current_user_id,
        moment_id: id
      }
    });

    let message = {
      avatar: ctx.authUser.avatar,
      user_id: current_user_id,
      type: 'like'
    }

    if(like){
      await like.destroy();
      ctx.apiSuccess(momentTimeline.moment.moment_likes);
    }else{
      await app.model.MomentLike.create({
        user_id: current_user_id,
        moment_id: id
      });
      ctx.apiSuccess(momentTimeline.moment.moment_likes);
    }

    // // 通知作者
    if(momentTimeline.moment.user_id && momentTimeline.moment.user_id !== current_user_id){
      ctx.sendAndSaveMessame(momentTimeline.moment.user_id, message, 'moment');
    }
    
    // 通知相关人
    momentTimeline.moment.moment_likes.forEach(item => {
      if (item.user_id !== current_user_id) {
        ctx.sendAndSaveMessame(item.user_id, message, 'moment');
      }
  });

    // if(momentTimeline.moment.user_id){
    //   ctx.sendAndSaveMessame(momentTimeline.moment.user_id, message, 'moment')
    // }
  }

  // 朋友圈评论
  async comment(){
    const { ctx, app } = this;
    let current_user_id = ctx.authUser.id;

    ctx.validate({
      id:{
        type: 'int',
        required: true,
        desc: '朋友圈消息id'
      },
      content: {
        type: 'string',
        required: true,
        desc: '评论内容'
      },
      reply_id: {
        type: 'int',
        required: true,
        defValue: 0,
        desc: '回复id'
      }
    });
    let { id,content,reply_id } = ctx.request.body;

    let momentTimeline = await app.model.MomentTimeline.findOne({
      where: {
        user_id: current_user_id,
        moment_id: id
      },
      include:[{
        model: app.model.Moment,
        attributes: ['user_id'],
        include: [{
          model: app.model.MomentLike,
          attributes: ['user_id']
        }]
      }]
    });

    if(!momentTimeline){
      return ctx.apiFail('朋友圈消息不存在')
    }

    let comment = await app.model.MomentComment.create({
      user_id: current_user_id,
      moment_id: id,
      content,
      reply_id
    });

    ctx.apiSuccess(comment);
    // 消息推送
    let message = {
      avatat: ctx.authUser.avatar,
      user_id: current_user_id,
      type: "comment"
    }

    // 通知作者
    if(momentTimeline.moment.user_id && momentTimeline.moment.user_id !== current_user_id){
      ctx.sendAndSaveMessame(momentTimeline.moment.user_id, message, 'moment');
    }
    // 通知相关人
    momentTimeline.moment.moment_likes.forEach(item => {
      if (item.user_id !== current_user_id) {
          ctx.sendAndSaveMessame(item.user_id, message, 'moment')
      }
    });
    // 通知被回复人
    if(reply_id > 0){
      let index = momentTimeline.moment.moment_likes.findIndex(item=> item.user_id === reply_id);
      // 如果不包含被被回复人 就推送给被回复人
      if(index === -1){
        ctx.sendAndSaveMessame(reply_id, message, 'moment')
      }
    }
  }


  // 朋友圈列表
  async timeline(){
    const { ctx, app } = this;
    let current_user_id = ctx.authUser.id;

    // 分页计算
    let page = ctx.params.page ? parseInt(ctx.params.page) : 1;
    let limit = ctx.query.limit ? parseInt(ctx.query.limit) : 10;
    let offset = (page - 1) * limit;
    console.log(page);
    let rows = await app.model.MomentTimeline.findAll({
      where: {
        user_id: current_user_id
      },
      include: [{
        model:app.model.Moment,
        include:[{
          // 评论人
          model: app.model.User,
          attributes: ['id', 'nickname', 'username', 'avatar']
        },{
          model:app.model.MomentComment,
          attributes: {
            exclude: ['created_at', 'updated_at']
          },
          include:[{
            // 关联评论的人
            model: app.model.User,
            as: "momentCommentUser",
            attributes: ['id', 'nickname', 'username']
          },{
            // 回复人
            model: app.model.User,
            as: "momentCommentReply",
            attributes: ['id', 'nickname', 'username']
          }]
        },{
          model: app.model.MomentLike,
          attributes: ['user_id', 'moment_id'],
          include:[{
             // 点赞人
            model: app.model.User,
            attributes: ['id', 'nickname', 'username']
          }]
        }]
      }],
      offset,
      limit,
      order: [
        ['id','DESC']
      ]
    });

    // 获取当前用户的所有好友
    let friends = await app.model.Friend.findAll({
      where: {
        user_id: current_user_id,
        lookhim: 1
      },
      attributes:['friend_id']
    });
    // 被好友
    let bfriends = await app.model.Friend.findAll({
      where: {
        friend_id: current_user_id,
        lookme: 1
      },
      attributes:['user_id']
    });

    // 把对象数组，转成字符串数组
    friends = friends.map(item => item.friend_id);      //  [1,2,3]
    bfriends = bfriends .map(item => item.user_id);     //  [2] (交集[2])

    friends = friends.filter(item=>bfriends.includes(item))

    // 整理格式
    let res = [];
    rows.forEach(item => {
      if (friends.includes(item.moment.user_id) || item.moment.user_id === current_user_id) {
          // 评论部分
        let comments = [];
        item.moment.moment_comments.forEach(v => {
          if(friends.includes(v.momentCommentUser.id) || v.momentCommentUser.id === current_user_id){
            comments.push({
              content: v.content, //评论内容
              user: {
                id: v.momentCommentUser.id,
                name: v.momentCommentUser.nickname || v.momentCommentUser.username
              },
              reply: v.momentCommentReply ? {
                id: v.momentCommentReply.id,
                name: v.momentCommentReply.nickname || v.momentCommentReply.username
              } : null
            })
          }
        })

        // 点赞部分
        let likes = [];
        item.moment.moment_likes.forEach(v =>{
          if(friends.includes(v.user.id) || v.user.id === current_user_id){
            likes.push({
              id: v.user.id,
              name: v.user.nickname || v.user.username
            })
          }
        })
        res.push({
          id: item.id,  // 时间轴id
          user_id: item.moment.user_id, //发布人的id
          user_name: item.moment.user.nickname || item.moment.user.username,  //发布人的昵称
          avatar: item.moment.user.avatar,  // 发布人头像
          moment_id: item.moment_id,  //朋友圈消息id
          content: item.moment.content, // 朋友圈消息内容
          image: item.moment.image ? item.moment.image.split(',') : [], // 朋友圈消息图片
          video: item.moment.video ? JSON.parse(item.moment.video) : null,  // 朋友圈消息视频
          location: item.moment.location, //位置
          own: item.own,  // 是否是自己的 0否1是
          created_at: item.created_at,
          comments, //评论
          likes // 点赞
        })
      }
    })
    ctx.apiSuccess(res)
  }



  // 某个用户的朋友圈列表
  async list(){
    const { ctx, app } = this;
    let current_user_id = ctx.authUser.id;

    // 分页计算
    let page = ctx.params.page ? parseInt(ctx.params.page) : 1;
    let limit = ctx.query.limit ? parseInt(ctx.query.limit) : 10;
    let offset = (page - 1) * limit;
    let user_id = ctx.query.user_id ? parseInt(ctx.query.user_id) : 0;

    let lookIds = [];

    if(!user_id){
      // 本人
      user_id = current_user_id;
      lookIds = false;
    } else {
      // 验证我是否具备查看用户的权限
      let f = await app.model.User.findOne({
        where: {
          id: user_id,
          status: 1
        },
        attributes: ['id', 'nickname', 'username', 'avatar'],
        include:[{
          model: app.model.Friend,
          as: "bfriends",
          where: {
            user_id: current_user_id
          },
          attributes:['lookhim','isblack']
        },{
          model: app.model.Friend,
          as: "friends",
          where: {
            friend_id: current_user_id
          },
          attributes:['lookme','isblack']
        }]
      })

      // 用户是否存在
      if (!f) {
        return ctx.apiFail("用户不存在或已被禁用")
      }
      // 是否是好友关系
      if(!f.bfriends.length || !f.friends.length){
        console.log("是否是好友关系");
        return ctx.apiSuccess([])
      }
      // 不可见(拉黑、不给我看)
      if (f.bfriends[0].isblack || f.friends[0].isblack || !f.bfriends[0].lookhim || !f.friends[0].lookme) {
        
        return ctx.apiSuccess([])
      }
      // 获取当前用户的所有好友（查找共同好友）
      let friends = await app.model.Friend.findAll({
        where: {
          user_id: current_user_id,
          isblack: 0
        },
        attributes: ['friend_id']
      });
      // 转成以为数组
      lookIds = friends.map(item=>item.friend_id);
    }

    let rows = await app.model.Moment.findAll({
      where: {
        user_id
      },
      include:[{
        // 评论人
        model: app.model.User,
        attributes: ['id', 'nickname', 'username', 'avatar']
      },{
        model:app.model.MomentComment,
        attributes: {
          exclude: ['created_at', 'updated_at']
        },
        include:[{
          // 关联评论的人
          model: app.model.User,
          as: "momentCommentUser",
          attributes: ['id', 'nickname', 'username']
        },{
          // 回复人
          model: app.model.User,
          as: "momentCommentReply",
          attributes: ['id', 'nickname', 'username']
        }]
      },{
        model: app.model.MomentLike,
        attributes: ['user_id', 'moment_id'],
        include:[{
           // 点赞人
          model: app.model.User,
          attributes: ['id', 'nickname', 'username']
        }]
      }],
      offset,
      limit,
      order: [
        ['id','DESC']
      ]
    });

    // 整理数据格式
    let res = [];
    rows.forEach(item => {
      let comments = [];
      item.moment_comments.forEach(v => {
        if(!lookIds || lookIds.includes(v.momentCommentUser.id) || v.momentCommentUser.id === current_user_id){
          comments.push({
            content: v.content, //评论内容
            user: {
              id: v.momentCommentUser.id,
              name: v.momentCommentUser.nickname || v.momentCommentUser.username
            },
            reply: v.momentCommentReply ? {
              id: v.momentCommentReply.id,
              name: v.momentCommentReply.nickname || v.momentCommentReply.username
            } : null
          })
        }
      });
      let likes = [];
      item.moment_likes.forEach(v => {
        if(!lookIds || lookIds.includes(v.user.id) || v.user.id === current_user_id){
          likes.push({
            id: v.user.id,
            name: v.user.nickname || v.user.username
          })
        }
      });

      res.push({
        user_id: item.user_id, //发布人的id
        user_name: item.user.nickname || item.user.username,  //发布人的昵称
        avatar: item.user.avatar,  // 发布人头像
        moment_id: item.id,  //朋友圈消息id
        content: item.content, // 朋友圈消息内容
        image: item.image ? item.image.split(',') : [], // 朋友圈消息图片
        video: item.video ? JSON.parse(item.video) : null,  // 朋友圈消息视频
        location: item.location, //位置
        own: 1,  // 是否是自己的 0否1是
        created_at: item.created_at,
        comments, //评论
        likes // 点赞
      })
    });
    ctx.apiSuccess(res);
  }
}

module.exports = MomentController;

